/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: CoinPairListPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.market.presenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.AppUI;
import io.bhex.app.event.FavoriteChangeEvent;
import io.bhex.app.market.bean.FavoriteRecordBean;
import io.bhex.app.utils.KlineUtils;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.UISafeKeeper;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.NewCoinPairListBean;
import io.bhex.sdk.quote.bean.QuoteTokensBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.quote.bean.TickerListBean;
import io.bhex.sdk.socket.NetWorkObserver;

/**
 * ================================================
 * 描   述: 币对列表
 * ================================================
 */

public class CoinPairListPresenter extends BasePresenter<CoinPairListPresenter.CoinPairListUI>{

    public interface CoinPairListUI extends AppUI{

        void showTabOfQuoteTokens(LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap);

        String getCurrentTab();

        String getExchangeId();

        void notifyDataChange(QuoteTokensBean.TokenItem tokenItem);
    }

    //创建tab 数据Map
    LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap = new LinkedHashMap<>();

    /**
     * 拼接行情参数
     *
     * @return
     */
    public String getSymbolsListStr() {
        StringBuffer stringBuffer = new StringBuffer();
        for (String key : tabMap.keySet()) {
            if (!key.equals(getString(R.string.string_favorite))) {//刷出自选,因为其他的列表已经包括
                QuoteTokensBean.TokenItem tokenItem = tabMap.get(key);
                if (tokenItem != null) {
                    HashMap<String, CoinPairBean> coinPairMap = tokenItem.getCoinPairMap();
                    if (coinPairMap != null) {
                        if (!coinPairMap.isEmpty()) {
                            for (String keyOfCoin : coinPairMap.keySet()) {
                                CoinPairBean coinPairBean = coinPairMap.get(keyOfCoin);
                                if (coinPairBean != null) {
                                    String symbol = coinPairBean.getSymbolId();
                                    if (stringBuffer.toString().length() > 0) {
                                        stringBuffer.append("," + symbol);
                                    } else {
                                        stringBuffer.append(symbol);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return stringBuffer.toString();
    }


    private void handleSocketMarketList(TickerBean tickerBean) {
        String currentTab = getUI().getCurrentTab();
        QuoteTokensBean.TokenItem currentTokenItem = tabMap.get(currentTab);
        for (String key : tabMap.keySet()) {
            QuoteTokensBean.TokenItem tokenItem = tabMap.get(key);
            if (tokenItem != null) {
                HashMap<String, CoinPairBean> coinPairMap = tokenItem.getCoinPairMap();
                if (coinPairMap != null) {
                    for (String coinKey : coinPairMap.keySet()) {
                        CoinPairBean coinPairBean = coinPairMap.get(coinKey);
                        String symbol = coinPairBean.getSymbolId();
                        String symbolTicker = tickerBean.getS();
                        if (symbol.equals(symbolTicker)) {
                            coinPairBean.setTicker(tickerBean);
                            if(currentTokenItem == tokenItem)
                                notifyCoinPairListDataChange(tabMap);
                        }

                    }

                }

            }
        }
    }


    @Override
    public void onUIReady(BaseCoreActivity activity, CoinPairListUI ui) {
        super.onUIReady(activity, ui);
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        getCoinPairList();
    }


    @Override
    public void onPause() {
        super.onPause();
        QuoteApi.UnSubTickers();
    }





    /**
     * 创建tab数据集
     * @param response
     */
    private LinkedHashMap<String, QuoteTokensBean.TokenItem> createTabMap(List<QuoteTokensBean.TokenItem> response) {
        tabMap.clear();
        List<QuoteTokensBean.TokenItem> tabList = response;
        if (tabList != null) {
            //添加 默认第一个tab为自选
            QuoteTokensBean.TokenItem itemFavorite = new QuoteTokensBean.TokenItem();
            itemFavorite.setTokenId(getString(R.string.string_favorite));
            itemFavorite.setTokenName(getString(R.string.string_favorite));
            itemFavorite.setTokenFullName(getString(R.string.string_favorite));
            tabList.add(0,itemFavorite);

            for (QuoteTokensBean.TokenItem tokenItem : tabList) {
                DebugLog.e("MAP",tokenItem.getTokenId() + tokenItem.getTokenFullName());
                tabMap.put(tokenItem.getTokenId(),tokenItem);
            }
        }
        return tabMap;
    }


    public void getCoinPairList() {
        SymbolDataManager.GetInstance().getNewCoinPairList(UISafeKeeper.guard(getUI(), new SimpleResponseListener<NewCoinPairListBean>() {


            @Override
            public void onSuccess(NewCoinPairListBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    if(response.quoteToken !=null) {

                        LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap = createTabMap(response.quoteToken);
                        getUI().showTabOfQuoteTokens(tabMap);
                        //getCoinPairList();
                        handCoinPairListData(response.symbol);
                        getRealTimeData();
                    }

                }
            }

        }));

    }



    /**
     * 处理币对列表数据
     * @param listBean
     */
    private void handCoinPairListData(List<CoinPairBean> listBean) {
        List<CoinPairBean> coinPairList = listBean;
        if (coinPairList != null&&!coinPairList.isEmpty()) {
            QuoteTokensBean.TokenItem favoriteToken = tabMap.get(getString(R.string.string_favorite));
            LinkedHashMap<String, CoinPairBean> favoriteMap = favoriteToken.getCoinPairMap();
            //登录添加网络同步的自选，
            if (UserInfo.isLogin()) {
                //如果登录了，先清空本地和内存中的自选
                if (favoriteMap != null) {
                    favoriteMap.clear();
                    KlineUtils.clearFavoriteRecord();
                }
            }

            for (CoinPairBean coinPairBean : coinPairList) {
                String quoteToken = coinPairBean.getQuoteTokenId();
                if (tabMap.containsKey(quoteToken)) {
                    QuoteTokensBean.TokenItem tabTokenItem = tabMap.get(quoteToken);
                    HashMap<String, CoinPairBean> coinPairMap = tabTokenItem.getCoinPairMap();
                    coinPairMap.put(coinPairBean.getBaseTokenId(),coinPairBean);
                }else{
                    DebugLog.w("market",quoteToken+" tab is null");
                }

                //登录添加网络同步的自选
                if (UserInfo.isLogin()) {

                    //单独处理添加自选
                    boolean isFavorite = SymbolDataManager.GetInstance().isFavorite(coinPairBean);
                    if (isFavorite) {

                        if (favoriteToken != null) {
                            favoriteMap.put(coinPairBean.getBaseTokenId(), coinPairBean);
                            //同时同步到本地
                            KlineUtils.saveFavorite(coinPairBean);
                        }
                    }
                }
            }

            //未登录，添加本地自选
            if (!UserInfo.isLogin()) {
                FavoriteRecordBean favoriteRecordBean = KlineUtils.getFavorite();
                List<CoinPairBean> dataFavorite = favoriteRecordBean.getData();
                if (dataFavorite != null) {
                    if (favoriteToken != null) {
                        for (CoinPairBean coinPairBean : dataFavorite) {
                            favoriteToken.getCoinPairMap().put(coinPairBean.getBaseTokenId(), coinPairBean);
//                            updateCoinListFavoriteStatus(coinPairBean);
                        }
                    }
                }
            }

            notifyCoinPairListDataChange(tabMap);
        }
    }

    /**
     * 提示币对数据更新
     * @param tabMap
     */
    private void notifyCoinPairListDataChange(LinkedHashMap<String, QuoteTokensBean.TokenItem> tabMap) {
        String currentTab = getUI().getCurrentTab();
        QuoteTokensBean.TokenItem tokenItem = tabMap.get(currentTab);
        getUI().notifyDataChange(tokenItem);
    }

    public void getRealTimeData(){
        String symbolsListStr = getSymbolsListStr();
        QuoteApi.SubTickers(symbolsListStr, new NetWorkObserver<TickerListBean>() {
            @Override
            public void onShowUI(TickerListBean response) {
                if (getUI() == null || !getUI() .isAlive() || response == null)
                    return;

                List<TickerBean> datas = response.getData();
                if (datas != null) {
                    for (TickerBean data : datas) {
                        handleSocketMarketList(data);
                    }
                }
            }

            @Override
            public void onError(String error) {
            }
        });

    }


    public void changePage(String tabName) {
        notifyCoinPairListDataChange(tabMap);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void OnMessageEvent(FavoriteChangeEvent event){
        updateCoinListFavoriteStatus(event.getCoin());
        QuoteTokensBean.TokenItem favoriteToken = tabMap.get(getString(R.string.string_favorite));
        FavoriteRecordBean favorite = KlineUtils.getFavorite();
        if (favorite != null) {
            List<CoinPairBean> favoriteList = favorite.getData();
            if (favoriteList != null) {
                if (favoriteToken != null) {
                    LinkedHashMap<String, CoinPairBean> coinPairMap = favoriteToken.getCoinPairMap();
                    coinPairMap.clear();
                    for (CoinPairBean datum : favoriteList) {
                        coinPairMap.put(datum.getBaseTokenId(),datum);
                    }
                    favoriteToken.setCoinPairMap(coinPairMap);
                }

            }
        }

        notifyCoinPairListDataChange(tabMap);
    }

    /**
     * 更新币对列表收藏的状态,保证行情列表收藏状态的同步
     * @param coinFav
     */
    private void updateCoinListFavoriteStatus(CoinPairBean coinFav) {
        if (coinFav == null) {
            return;
        }
        String baseTokenId = coinFav.getSymbolId();
        boolean isFavorite = SymbolDataManager.GetInstance().isFavorite(coinFav);
        for (String key : tabMap.keySet()) {
            QuoteTokensBean.TokenItem tokenItem = tabMap.get(key);
            LinkedHashMap<String, CoinPairBean> coinPairMap = tokenItem.getCoinPairMap();
            if (coinPairMap != null) {
                for (String itemKey : coinPairMap.keySet()) {
                    CoinPairBean coinPairBean = coinPairMap.get(itemKey);
                    if (coinPairBean.getSymbolId().equals(baseTokenId)) {
                        coinPairBean.setFavorite(isFavorite);
                        break;
                    }

                }
            }

        }

    }
}
